/*  Jarpa 1.05 - Java Packaging for Flash Lite Developers
 * 
 *  Recently, a new generation of mobile phones with support for Java ME and Flash Lite 
 *  has been taking widespread acceptance by the market, opening the door
 *  for hybrid applications. Looking for this business potential Jarpa was created
 *  allowing Flash Lite Developers deliver their content as Java ME applications.
 * 
 *  @author Felipe Andrade <felipe.andrade@i2tecnologia.com.br>
 * 
 *  http://www.i2tecnologia.com.br/jarpa/
 *  http://blog.felipeandrade.org/
 *  http://www.biskero.org
 */

package com.i2tecnologia.jarpa;

import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
//import javax.microedition.location.*;

public class Jarpa extends MIDlet implements CommandListener, Runnable {
    private Form _form;
    private Command _cmdExit;
    private StringItem _status;
    private StringItem _statusRead;
    
    // values short than 20 sometimes close the midlet
    private static int MAX_INTERVAL = 20;
    
    // target folder
    private String _targetFolder = "file:///E:/Others/Jarpa_105.swf";
    
    // sample increment
    private int _inc = 0;
    
    public void startApp() {
        _form = new Form("Jarpa Debug");        
        _cmdExit = new Command("Exit", Command.EXIT, 1);
        _status = new StringItem("Teste STR", "");
        _statusRead = new StringItem("", "");
        
        _form.append(_status);
        _form.append(_statusRead);
        
        _form.addCommand(_cmdExit);
        _form.setCommandListener(this);
        Display.getDisplay(this).setCurrent(_form);
        
        new Thread(this).start();
    }
    
    public void pauseApp() {}
    public void destroyApp(boolean aCond) {}

    public void run() {
        try {
            Resources.getInstance().copyResources(_targetFolder);
            platformRequest(_targetFolder);
        } catch(Exception e) {
            _status.setText("Error: " + e.toString());
        }
        
        while(true) {
            _status.setText("Status: " + Connection.getInstance()._status);
            
            try {
                String sent = "" + (++_inc);
                String recv = "";
                
                try {
                    Connection.getInstance().write(sent);
                    recv = Connection.getInstance().read(); 
                } catch (Exception e) {
                    destroyApp(true);
                    notifyDestroyed();
                }
                
                _statusRead.setText("Write: " + sent + "\nRead: " + recv + " / len: " + recv.length() );
                Thread.sleep(MAX_INTERVAL);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
    
    public void commandAction(Command aCmd, Displayable aDisplay) {
        destroyApp(true);
        notifyDestroyed();
    }
}
